#pragma once

#include <iostream>
#include <string>
#include <functional>
#include <cerrno>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "err.hpp"

namespace nt_server
{
    const uint16_t default_port = 8888; // 默认端口号
    const int backlog = 32;             // 全连接队列的最大长度

    using func_t = std::function<std::string(std::string)>; // 回调函数类型

    class TcpServer
    {
    public:
        TcpServer(const func_t &func, const uint16_t port = default_port)
            : func_(func), port_(port), quit_(false)
        {
        }

        ~TcpServer()
        {
        }

        // 初始化服务器
        void InitServer()
        {
            // 1.创建监听套接字
            listensock_ = socket(AF_INET, SOCK_STREAM, 0);
            if (listensock_ == -1)
            {
                std::cerr << "Create ListenSocket Fail!" << strerror(errno) << std::endl;
                exit(SOCKET_ERR);
            }

            std::cout << "Create ListenSocket Success! " << listensock_ << std::endl;

            // 2.绑定IP地址与端口号
            struct sockaddr_in local;
            memset(&local, 0, sizeof(local)); // 清零
            local.sin_family = AF_INET;
            local.sin_addr.s_addr = INADDR_ANY; // 绑定任意可用IP地址
            local.sin_port = htons(port_);

            if (bind(listensock_, (const sockaddr *)&local, sizeof(local)))
            {
                std::cout << "Bind IP&&Port Fail: " << strerror(errno) << std::endl;
                exit(BIND_ERR);
            }

            // 3.监听
            if (listen(listensock_, backlog) == -1)
            {
                std::cerr << "Listen Fail!" << strerror(errno) << std::endl;
                exit(LISTEN_ERR);
            }

            std::cout << "Listen Success!" << std::endl;
        }

        // 启动服务器
        void StartServer()
        {
            while (!quit_)
            {
                // 1.处理连接请求
                struct sockaddr_in client;
                socklen_t len = sizeof(client);

                int sock = accept(listensock_, (struct sockaddr *)&client, &len);

                // 2.如果连接失败，继续尝试连接
                if (sock == -1)
                {
                    std::cerr << "Accept Fail!" << strerror(errno) << std::endl;
                    continue;
                }

                // 连接成功，获取客户端信息
                std::string clientip = inet_ntoa(client.sin_addr);
                uint16_t clientport = ntohs(client.sin_port);

                std::cout << "Server accept " << clientip + "-" << clientport << " " << sock << " from " << listensock_ << " success!" << std::endl;

                // 3.根据 sock 套接字进行通信
                Service(sock, clientip, clientport);
            }
        }

        // 业务处理
        void Service(int sock, const std::string& clientip, const uint16_t& clientport)
        {
            char buff[1024];
            std::string who = clientip + "-" + std::to_string(clientport);
            while (true)
            {
                ssize_t n = read(sock, buff, sizeof(buff) - 1); // 预留 '\0' 的位置
                if (n > 0)
                {
                    // 读取成功
                    buff[n] = '\0';
                    std::cout << "Server get: " << buff << " from " << who << std::endl;

                    std::string respond = func_(buff); // 实际业务处理由上层指定

                    // 发送给服务器
                    write(sock, buff, strlen(buff));
                }
                else if (n == 0)
                {
                    // 表示当前读取到文件末尾了，结束读取
                    std::cout << "Client " << who << " " << sock << " quit!" << std::endl;
                    close(sock); // 关闭文件描述符
                    break;
                }
                else
                {
                    // 读取出问题（暂时）
                    std::cerr << "Read Fail!" << strerror(errno) << std::endl;
                    close(sock); // 关闭文件描述符
                    break;
                }
            }
        }

    private:
        int listensock_; // 监听套接字
        uint16_t port_;  // 端口号
        bool quit_;      // 判断服务器是否结束运行
        func_t func_;    // 回调函数
    };
}